package com.msstudio.game.basic;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import org.webbitserver.WebSocketConnection;

import com.msstudio.game.BasicUserPlayer;
import com.msstudio.message.Msg;


/**
 * @author sunnyz
 * Channel 就是很多WebSocketConnection(每一个WebSocketConnection对应唯一一个player)的集合
 * 用户群发消息.
 *
 */
public class Channel {
	private static final java.util.logging.Logger logger = Logger.getLogger(Channel.class.getName());
	
	
	private final Set<WebSocketConnection> connectionSet = Collections
			.synchronizedSet(new HashSet<WebSocketConnection>());
	
	public Channel() {}
	
	/**
	 * sessionSet已经是线程安全的,所以以下的方法都不需要用synchronized()
	 * @param userPlayer
	 * @return
	 */
	public Set<WebSocketConnection> join(BasicUserPlayer userPlayer) {
		WebSocketConnection connection = userPlayer.getConnection();
		if (!connectionSet.contains(connection)) {
			connectionSet.add(connection);
		}
		return connectionSet;		
	}

	public void leave(BasicUserPlayer userPlayer) {
		WebSocketConnection connection = userPlayer.getConnection();
		if (connectionSet.contains(connection)) {
			connectionSet.remove(connection);
		}	
	}
	
	public Set<WebSocketConnection> getConnectionSet() {
		return this.connectionSet;
	}
	
	/**
	 * 发送消息给该channel的所有用户
	 */
	public void broadcast(Msg msg) {
		for(WebSocketConnection connection : connectionSet) {
			if (connection != null) {
				try {
					connection.send(msg.toByteArray());
				} catch (IOException e) {
					logger.severe("Failed to broadcast:" + e.getMessage());
				}
			}
		}

	}
	
	/**
	 * 发送消息给区域(一间房,一个地图,整个服务器除自己之外的所有的用户
	 */
	public void broadcastToOthers(Msg msg, String me) {
		for(WebSocketConnection connection : connectionSet) {
			if (connection != null) {
				try {
					connection.send(msg.toByteArray());
				} catch (IOException e) {
					logger.severe("Failed to broadcast to others:" + e.getMessage());
				}
			}
		}
	}
}
